//封装请求的方法
export function getUrlRules(url) {
    var url_rules = [
        '/api/rooms/list.html',
        '/api/player/login.html',
        '/api/player/send-email.html',
        '/api/player/register.html',
    ];
    for (var i in url_rules) {
        if (url_rules[i] == url) {
            return true;
        }
    }
    return false;
}

// 发送post 请求
export function post(url, params = {}, responseType = '', contentType = 'application/json;charset=UTF-8') {
    if (!this.$localGet('bakal_player_token') && !getUrlRules(url)) {
        this.$notify.warning({ title: 'Warning', message: '用户信息失效，需要重新登录'});
        return false;
    }


    let res_headers = {
        'Content-type': contentType
    }
    if (this.$localGet('bakal_player_token')) {
        res_headers.Authorization = `Bearer ${this.$localGet('bakal_player_token')}`;
    }
    
    for (var i in params) {
        if (params[i] == "" && params[i] !== 0) {
            delete params[i];
        }
    }
    
    return new Promise((resolve, reject) => {
        this.$axios.post(url, params, {
            headers: res_headers,
            responseType: responseType,
            timeout: 120 * 1000
        }).then(response => {
            resolve(response.data)
        }).catch(err => {
            if (err.response.data.code == 999){
                // 删除token
                this.$localClear();
                // 重置 $store
                this.$store.commit('changeUsersInfo', {});
                this.$store.commit('changeUsersToken', "");
                this.$store.commit('changeStatus', false);
                // 提示
                this.$notify.warning({ title: 'Warning', message: '用户信息失效，需要重新登录' });
            } else if (err.response.data.code == 302) {
                this.$notify.error({ title: '', message: err.response.data.msg });
                this.$router.push('/');
            } else {
                this.$notify.error({ title: 'Error', message: "链接服务器失败" });
            }
            reject(err)
        })
    })
}
